package com.starblink.mine.personhome.ui.wishlist.ui.wishlistitems.ui

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.utils.bindingAdapter
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.linear
import com.starblink.android.basic.brv.utils.models
import com.starblink.android.basic.brv.utils.setup
import com.starblink.android.basic.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.setEmptyViewForWishTemplate
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.basic.log.SKLogger
import com.starblink.mine.R
import com.starblink.mine.databinding.FragmentWishlistItemsBinding
import com.starblink.mine.databinding.ItemWishlistCollectProductBinding
import com.starblink.rocketreserver.FetchCollectProductsByAccountIdV3Query
import kotlinx.coroutines.launch

/**
 * 个人中心-客态-Wishlist子页-Items子页
 */
class WishlistItemsFragment : BaseTVMFragment<FragmentWishlistItemsBinding, WishlistItemsVM>() {

    companion object {
        private const val TAG = "WishlistItemsFragment"
        fun newInstance(accountId: String, accountDeleted: Boolean = false) =
            WishlistItemsFragment().apply {
                arguments = bundleOf(
                    MineManager.KEY_USER_ID to accountId,
                )
            }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentWishlistItemsBinding {
        return FragmentWishlistItemsBinding.inflate(inflater, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SKLogger.e("dss", "WishlistItemsFragment-onCreate")
    }

    override fun initData() {
        arguments?.run {
            getString(MineManager.KEY_USER_ID)?.let {
                viewModel.accountId = it
            }
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        //初始化列表相关
        viewBinding.rv.linear().divider {
            setColor(Color.TRANSPARENT)
            setDivider(12, true)
            startVisible = true
            endVisible = true
        }.setup {
            addType<FetchCollectProductsByAccountIdV3Query.ProductList, ItemWishlistCollectProductBinding>(
                it
            )

            onBind {
                val viewBinding = getBinding<ItemWishlistCollectProductBinding>()
                val product =
                    getModel<FetchCollectProductsByAccountIdV3Query.ProductList>().productF

                viewBinding.root.setData(
                    product = product,
                    position = layoutPosition,
                    spmPageValue = SpmPageDef.Page_10212,
                    deleteClickCallback = {
                    }, choiceClickCallback = {})
            }
        }

        viewBinding.page.onEmpty {
            post {
                setEmptyViewForWishTemplate(
                    title = "No items yet",
                    subTitle = "This account has not added \nanything to Items",
                    marginTop = 32.dp,
                )
            }
        }
        viewBinding.page.onError {
            val view = findViewById<ImageView>(R.id.icon)
            (view.layoutParams as ViewGroup.MarginLayoutParams)
                .setMargins(0, 53.dp, 0, 0)
        }

        viewBinding.page.onLoading {
            val ll = findViewById<LinearLayout>(R.id.ll_loading)
            (ll.layoutParams as ViewGroup.MarginLayoutParams)
                .setMargins(0, 141.dp, 0, 0)
        }

        viewBinding.page.onRefresh {
            viewModel.getCollectProducts(refresh = true)
        }
        viewBinding.page.onLoadMore {
            viewModel.getCollectProducts(refresh = false)
        }
    }

    override fun startObserve() {
        iniEventListener()

        viewModel.listResponseLiveData.observe(this) {
            if (viewBinding.rv.models.isNullOrEmpty() || it.refresh) {
                // 刷新或页面销毁恢复
                viewBinding.page.addData(ArrayList(it.totalList)) {
                    it.totalList.isNotEmpty()
                }
            } else {
                // 加载更多
                viewBinding.page.addData(it.pageList) {
                    it.pageList.isNotEmpty()
                }
            }
        }

        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError()
                }
            }
        }

        // 客态-加载数据
        viewBinding.page.showLoading(refresh = true)
    }

    private fun iniEventListener() {
        // 监听商品收藏事件
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) {
            SKLogger.e("dss", "WishlistItemsFragment-CollectProductEvent")
            // 个人首页-客态-Wishlist子页-Items子页，当商品收藏状态发生修改时，更新状态
            if (viewModel.listResponseLiveData.value != null) {
                lifecycleScope.launch {
                    for ((index, product) in viewModel.listResponseLiveData.value!!.totalList.withIndex()) {
                        if (it.id == product.productF.id && it.collect != product.productF.collected) {
                            SKLogger.e("dss", "WishlistItemsFragment发现Product要修改")
                            product.productF.apolloValue("collected", it.collect)
                            viewBinding.rv.bindingAdapter.notifyItemChanged(index)
                            break
                        }
                    }
                }
            }
        }
    }

}